package com.wn.manpower.web;

import com.wn.common.PageBean;
import com.wn.common.ResponseEntity;
import com.wn.entity.ChangePosts;
import com.wn.entity.Hr;
import com.wn.manpower.service.ChangePostsService;
import com.wn.manpower.service.HumanResourcesService;
import com.wn.manpower.vo.ChangePostsVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 调岗申请
 *
 * @author dzj
 * date: 2022/10/20
 */
@Slf4j
@RestController
@RequestMapping("/manpower/changeposts")
public class ChangePostsController {

    @Autowired
    ChangePostsService changePostsService;

    @Autowired
    HumanResourcesService humanResourcesService;

    /**
     * 调岗流程实例,设置流程变量的值，添加流程数据
     */
    @RequestMapping("/add")
    public ResponseEntity add(@RequestBody ChangePostsVo changePostsVo, HttpServletRequest request) {
//        获取流程引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
//        获取RunTimeService
        RuntimeService runtimeService = processEngine.getRuntimeService();
//        流程定义key
        String key = "changeposts";

//       创建变量集合
        Map<String, Object> map1 = new HashMap<>();
//      设置user1的取值，用户可以在界面上设置流程的执行  申请人
        map1.put("user1", changePostsVo.getUser1());
        //下一个任务负责人
        Map<String, Object> map2 = new HashMap<>();
        map2.put("user2", changePostsVo.getUser2());
//        启动流程实例，并设置流程变量的值（把map1传入）        单独写个方法，同时调用并行执行
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey(key, map1);

        //通过界面传输的id获得hr实例，得知其名字
        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = humanResourcesService.getById(userId);
//        获取taskService  实例申请同时完成第一步
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(hr.getWorkNumber())  //要查询的负责人 此处记得先查询HR表获得工号
                .singleResult();
        //完成任务的时候设置下一个负责人  前端记得传输负责人
        taskService.complete(task.getId(), map2);
        log.debug("申请执行完成", "下一负责人" + changePostsVo.getUser2());

        //查询下一个负责人任务
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(changePostsVo.getUser2())//只查询该任务负责人的任务
                .list();

        //处理完成后 查询出当前任务id加入到数据库表格
        changePostsVo.getChangePosts().setActivitiInstanceId(tasks.get(0).getId());
        changePostsService.add(changePostsVo.getChangePosts());

        return ResponseEntity.success;
    }

//----------------------------------add完成  前端记得传输负责人--------------------------

    /**
     * 查询当前个人待执行的任务,就是点击页面，直接展示自己的任务
     *
     * 通过用户id，获得当前用户的任务id
     * 通过任务id，多条件查询表格
     */
    @RequestMapping("/getTask")
    public ResponseEntity getTask(HttpServletRequest request) {
        String key = "changeposts";
        //通过界面传输的id获得hr实例，得知其名字
        int userId = Integer.parseInt(request.getHeader("userId"));
        Hr hr = humanResourcesService.getById(userId);

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(hr.getName())//只查询该任务负责人的任务
                .list();

        List<ChangePosts> changePostsList = null;

        for (int i = 0; i < tasks.size(); i++) {
            //通过任务id查询数据
            ChangePosts changePosts = changePostsService.getByActivitiInstanceId(tasks.get(i).getId());
            changePostsList.add(changePosts);
        }

        return new ResponseEntity(changePostsList);
    }

//----------------------获取自己的任务-----------------

    /**
     * 完成任务
     */
    @RequestMapping("/down")
    public ResponseEntity down(@RequestBody ChangePostsVo changePostsVo) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        Map<String, Object> map = new HashMap<>();
        map.put("user2", changePostsVo.getUser2());

        String key = "changeposts";
//        int userId = Integer.parseInt(request.getHeader("userId"));
//        Hr hr = humanResourcesService.getById(userId);
//        Task task = taskService.createTaskQuery()
//                .processDefinitionKey(key) //流程Key
//                .taskAssignee(hr.getName())  //要查询的负责人
//                .singleResult();

//        完成任务,参数：任务id
        taskService.complete(changePostsVo.getChangePosts().getActivitiInstanceId(), map);

        //查询下一个负责人任务   此处查询，引使用流程实例id进行查询，而不是用负责人
        Task task = taskService.createTaskQuery()
                .processDefinitionKey(key) //流程Key
                .taskAssignee(changePostsVo.getUser2())//只查询该任务负责人的任务
                .singleResult();  // singleResult 单个   list 多个

        changePostsVo.getChangePosts().setActivitiInstanceId(task.getId());
        changePostsService.update(changePostsVo.getChangePosts());

        return ResponseEntity.success;
    }

//----------------------完成自己的任务-----------------


    @RequestMapping("/update")
    public ResponseEntity update(@RequestBody ChangePosts changePosts) {
        changePostsService.update(changePosts);
        return ResponseEntity.success;
    }

    @RequestMapping("/getById/{id}")
    public ResponseEntity getById(@PathVariable int id) {
        ChangePosts changePosts = changePostsService.getById(id);
        return new ResponseEntity(changePosts);
    }

    @RequestMapping("/getPageByCondition")
    public ResponseEntity getByCondition(@RequestBody ChangePostsVo changePostsVo) {
        log.debug("changePostsVo:{}", changePostsVo);
        PageBean<ChangePosts> pageBean = changePostsService.getPageByCondition(changePostsVo.getChangePosts(), changePostsVo.getCurrPage(), changePostsVo.getPageSize());
        return new ResponseEntity(pageBean);
    }

    @RequestMapping("/del/{id}")
    public ResponseEntity del(@PathVariable int id) {
        changePostsService.del(id);
        return ResponseEntity.success;
    }
}
